<template>
  <el-form :model="loginForm" :rules="rules" ref="loginForm" class="login-container" label-position="left"
           label-width="0px">
    <h3 class="login_title">账号登录</h3>
    <el-form-item prop="userName">
      <el-input type="text" v-model="loginForm.userName" auto-complete="off" placeholder="用户名"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password" auto-complete="off" placeholder="密码" show-password>
      </el-input>
    </el-form-item>
    <el-form-item style="width: 100%">
      <el-button type="primary" style="width: 100%;background: #505458;border: none" @click="login('loginForm')">登录
      </el-button>
    </el-form-item>
    <el-form-item>没有账号？<el-button type="text" style="color:#1a5b59;font-weight:bold" @click="register()">注册</el-button></el-form-item>
  </el-form>
</template>

<script>
import api from '@/apis/api';
export default {
  name:'login',
  data() {
    return {
      rules: {
        userName: [{
          required: true,
          message: '用户名不能为空',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }]
      },
      checked: true,
      loginForm: {
        userName: '',
        password: ''
      },
      loading: false
    }
  },
  mounted() {
    //绑定事件，其他界面可能要写在methods里
    window.addEventListener('keydown', this.keyDown);
  },
  methods: {
    keyDown(e) {
      //如果是按回车则执行登录方法
      if (e.keyCode === 13) {
        this.login('loginForm')
      }
    },
    register(){
      // 向父组件传参，将当前登录组件切换为注册组件
      this.$emit("status",'register')
    },
    login() {
      let loginData = {
        'username': this.loginForm.userName,
        'password': this.loginForm.password
      };
      let _this = this;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          api.login(loginData).then(res => {
            if (res.code === 200) {
              //登录成功，先初始化vuex,然后将token和用户名添加到store
              _this.$store.commit('vuexInit');
              _this.$store.commit('setToken',res.data['token']);
              _this.$store.commit('setRootFolder',{folderId:res.data['folderId'],folderName:_this.loginForm.userName});
              _this.$store.commit('setFolder',{folderId:res.data['folderId'],folderName:_this.loginForm.userName});
              _this.$store.commit('setUserName',_this.loginForm.userName);
              // 路由跳转到首页根目录
              _this.$router.replace({
                path: '/'
              });
            } else {
              //登录失败显示错误信息
              _this.$alert(res.message, '提示', {
                confirmButtonText: '确定'
              })
            }
          })
        }
      });
    }
  },
}
</script>

